package io.wjc.service;

import io.wjc.model.PermissionVo;
import io.wjc.model.RoleVo;
import io.wjc.model.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService implements UserDetailsService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    //根据账号查询用户信息
    public UserVo getUserByUsername(String username){
        String sql = "select id,username,password,status from sys_user where username = ?";
        //连接数据库查询用户
        List<UserVo> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserVo.class));
        if(list !=null && list.size()==1){
            return list.get(0);
        }
        return null;
    }

    //根据账号查询角色信息
    public List<RoleVo> getRolesByUserId(Integer userId){
        String sql = "SELECT r.ID AS id,r.ROLE_NAME AS roleName FROM  sys_user u\n" +
                "LEFT JOIN sys_user_role x ON u.id=x.UID\n" +
                "LEFT JOIN sys_role r ON r.ID = x.RID\n" +
                "WHERE u.id = ?";
        //连接数据库查询用户
        List<RoleVo> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(RoleVo.class));
        return list;
    }

    //根据用户id查询用户权限
    public List<String> getPermissionsByUserId(Integer userId){
        String sql = "SELECT  m.permission_NAME AS code,m.permission_url AS url FROM  sys_user u\n" +
                "LEFT JOIN sys_user_role r ON u.id=r.UID\n" +
                "LEFT JOIN sys_role_permission p ON r.RID=p.RID\n" +
                "LEFT JOIN sys_permission m ON p.PID=m.ID\n" +
                "WHERE u.id = ?\n";

        List<PermissionVo> list = jdbcTemplate.query(sql, new Object[]{userId}, new BeanPropertyRowMapper<>(PermissionVo.class));
        List<String> permissions = new ArrayList<>();
        list.forEach(c -> permissions.add(c.getCode()));
        return permissions;
    }

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        //将来连接数据库根据账号查询用户信息
        UserVo userVo = getUserByUsername(name);
        if(userVo == null){
            //如果用户查不到，返回null，由provider来抛出异常
            return null;
        }
        //根据用户的id查询用户的权限
        List<String> permissions = getPermissionsByUserId(userVo.getId());
        //将permissions转成数组
        String[] permissionArray = new String[permissions.size()];
        permissions.toArray(permissionArray);
        UserDetails userDetails = User.withUsername(userVo.getUsername()).password(userVo.getPassword()).authorities(permissionArray).build();
        return userDetails;
    }
}
